package pers.qianyu.month_202012.date_20201220;

import org.junit.*;

import java.util.*;

/**
 * 49. 字母异位词分组
 * https://leetcode-cn.com/problems/group-anagrams/
 *
 * @author mizzle rain
 * @date 2020-12-20 14:24
 */
public class GroupAnagrams {
    // 排序
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String k = new String(chars);
            if (map.containsKey(k)) {
                map.get(k).add(str);
            } else {
                ArrayList<String> al = new ArrayList<>();
                al.add(str);
                map.put(k, al);
            }
        }
        return new ArrayList<>(map.values());
    }

    // 字母计数
    public List<List<String>> groupAnagrams2(String[] strs) {
        HashMap<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            int[] dict = new int[26];
            for (int i = 0; i < str.length(); i++) {
                dict[str.charAt(i) - 'a']++;
            }
            StringBuilder builder = new StringBuilder();
            // 将每个出现次数大于 0 的字母和出现次数按顺序拼接成字符串，作为哈希表的键
            for (int i = 0; i < 26; i++) {
                if (dict[i] > 0) {
                    builder.append((char) (i + 'a')).append(dict[i]);
                }
            }
            String k = builder.toString();
            if (map.containsKey(k)) {
                map.get(k).add(str);
            } else {
                ArrayList<String> al = new ArrayList<>();
                al.add(str);
                map.put(k, al);
            }
        }
        return new ArrayList<>(map.values());
    }

    @Test
    public void test1() {
        String[] arr = {"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> result = new GroupAnagrams().groupAnagrams2(arr);
        result.forEach(System.out::println);
    }
}
